<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose title="人员" :width="500" @ok="handleOk">
    <a-tree
      checkable
      @check="onCheck"
      v-model:checkedKeys="checkedKeys"
      :field-names="{ title: 'title', key: 'pluraCode' }"
      :tree-data="treeData"
      :load-data="onLoadData"
  /></BasicModal>
</template>
<script setup lang="ts">
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { selectPersonTreeList } from './service';
  const emit = defineEmits(['register', 'success']);
  const treeData = ref([]);
  const selectKeys = ref([]);
  const checkedKeys = ref([]);
  const recordRows = ref([]);
  const only = ref(); //是否单选
  const onLoadData = (treeNode) => {
    return new Promise((resolve) => {
      if (treeNode.dataRef.children) {
        resolve();
        return;
      }
      selectPersonTreeList({ pid: treeNode.dataRef.id, type: 1 }).then((res) => {
        res.forEach((item) => {
          item.pluraCode = item.desc?.psnNum || item.code;
          item.pluraName = item.desc?.psnName || '';
        });
        treeNode.dataRef.children = res || [];
        treeData.value = [...treeData.value];
        resolve();
      });
    });
  };
  const handleOk = () => {
    emit('success', { checkedKeys, recordRows });
    closeModal();
  };
  const onCheck = (option, checkedNodes) => {
    selectKeys.value = option;
    if (only.value) {
      recordRows.value = checkedNodes.node;
      checkedKeys.value = [];
      checkedKeys.value = [checkedNodes.node.pluraCode];
    } else {
      recordRows.value = checkedNodes.checkedNodes;
    }
  };
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    only.value = data.isOnly;
    checkedKeys.value = data.list;
    selectPersonTreeList().then((res) => {
      res.forEach((item) => {
        item.pluraCode = item.desc?.psnNum || item.code;
        item.pluraName = item.desc?.psnName || '';
      });
      treeData.value = res || [];
    });
  });
</script>
<style lang="less" scoped></style>
